#ifndef  LRUCACHE_H
#define  LRUCACHE_H

#include "mutexlock.hpp"
#include "tcpconnection.hpp"
#include <list>
namespace  moqi
{

template<typename Key,typename Value>
class LRUCache
{

public:
	LRUCache() :_capacity(0) {

	}
	LRUCache(int capacity) :_capacity(capacity) {

	}
	~LRUCache() {

	}
	Value get(Key key) {
		if (cache.count(key) == 0) {//如果缓存中没有这个key	
			return -1;
		}
		else {//如果缓存中有这个key
			list<int>::iterator temp = key_to_list[key]; //获取其在list中的位置
			frequency.splice(frequency.begin(), frequency, key_to_list[key]);//将访问记录提前
			return cache[key];
		}

	}
	void put(int key, int value) {
		if (cache.count(key) == 0) {//如果缓存中没有这个key
			//需要判断是否满了
			if (cache.size() == _capacity) {//执行淘汰算法
				int deletekey = frequency.back();//访问记录的最后一个删除
				frequency.pop_back();
				key_to_list.erase(deletekey);
				cache.erase(deletekey);
				
			}
			cache[key] = value;//添加入缓存
			frequency.push_front(key);//插入到头
			key_to_list[key] = frequency.begin();
			
		}
		else {//如果缓存中有这个key
			list<int>::iterator temp = key_to_list[key]; //获取其在list中的位置
			frequency.splice(frequency.begin(), frequency, key_to_list[key]);//将访问记录提前
            cache[key] = value;
            key_to_list[key] = frequency.begin();
		}
	
	}
private:
	unordered_map<int, int> cache;//存储缓存数据
	unordered_map<key, value> key_to_list;//存储key到list的映射
	list<key>frequency; //存储访问记录
	int _capacity = 0;
};

}//end of namespace moqi
#endif
